package com.tiger.admin.http.schoolDept;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tiger.admin.Db;
import com.tiger.db.entity.SchoolDept;
import com.tiger.utils.ResponseUtil;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class SchoolDeptService {
    private final Db db;

    public SchoolDeptService(Db db) {
        this.db = db;
    }

    public List<SchoolDept> querySubDeptsByCode(String code) {
        List<SchoolDept> result = new ArrayList<>();
        SchoolDept dept = db.schoolDept.getOne(new LambdaQueryWrapper<SchoolDept>().select(SchoolDept::getId, SchoolDept::getTopId, SchoolDept::getLevel).eq(SchoolDept::getCode, code));
        if(dept == null) {
            return null;
        }

        LambdaQueryWrapper<SchoolDept> queryWrapper = new LambdaQueryWrapper<>();
        if(dept.getTopId() == 0) { //如果是最顶级的班级
            queryWrapper.eq(SchoolDept::getTopId, dept.getId());
        }else {
            queryWrapper.eq(SchoolDept::getTopId, dept.getTopId());
            queryWrapper.gt(SchoolDept::getLevel, dept.getLevel());
        }

        List<SchoolDept> depts = db.schoolDept.list(queryWrapper);

        recursive(depts, dept.getId(), result);

        return result;

    }

    private void recursive(List<SchoolDept> rows, Integer parentId, List<SchoolDept> target) {
        for(SchoolDept row : rows) {
            if(Objects.equals(row.getParentId(), parentId)) {
                target.add(row);
                recursive(rows, row.getId(), target);
            }
        }
    }

}
